package fr.utbm.lo53;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;

public class Network
{
	private static Network instance = null;
	
	public Activity MyActivity;
	private DatagramSocket SocketUDP;
	
	
	protected Network(Activity MyActivity)
	{
		this.MyActivity = MyActivity;
		try {
			SocketUDP = new DatagramSocket(6666);
			SocketUDP.setBroadcast(true);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	
	// retrieve the Broadcasting address.
	// http://code.google.com/p/boxeeremote/wiki/AndroidUDP
	InetAddress getBroadcastAddress() throws IOException
    {
		WifiManager wifi = (WifiManager) MyActivity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
		DhcpInfo dhcp = wifi.getDhcpInfo();
		// handle null somehow
		
		int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
		byte[] quads = new byte[4];
		for (int k = 0; k < 4; k++)
			quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
		
		return InetAddress.getByAddress(quads);
    }
	
	
	InetAddress getMyAddress() throws IOException
	{
		WifiManager wifi = (WifiManager) MyActivity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
		DhcpInfo dhcp = wifi.getDhcpInfo();
		
		int ip = dhcp.ipAddress;
		byte[] quads = new byte[4];
		for (int k = 0; k < 4; k++)
			quads[k] = (byte) ((ip >> k * 8) & 0xFF);
		
		return InetAddress.getByAddress(quads);
	}
	
	
	public void startMeasure() {
		System.out.println("Start measure");
		long startTime = System.currentTimeMillis();
		long duree = 500; 
		PacketVide packet = null;
		try {
			packet = new PacketVide(getBroadcastAddress(),6665);
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		while((System.currentTimeMillis() - startTime) < duree)
		{
			System.out.println("Send = " + (startTime - System.currentTimeMillis()) + " = " + duree);
			try {
				SocketUDP.send(packet.getPacket());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public void sendPositionTomcat(String x, String y, String mid) {
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
		nameValuePairs.add(new BasicNameValuePair("MEASURE", "true"));
		nameValuePairs.add(new BasicNameValuePair("X", x));
		nameValuePairs.add(new BasicNameValuePair("Y", y));
		nameValuePairs.add(new BasicNameValuePair("mid", mid));
		HttpPost httppost = new HttpPost("http://" + Settings.getInstance().getIp() + ":" + Settings.getInstance().getPort());
		try {
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		HttpClient httpclient = new DefaultHttpClient();
		try {
			httpclient.execute(httppost);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	// Singleton Pattern
	public static Network getInstance()
	{
		return instance;
	}
	
	// Singleton Pattern
	public static Network createInstance(Activity MyActivity)
	{
		if(instance == null)
		{
			instance = new Network(MyActivity);
		}
		return instance;
	}
	
}
